<?php

namespace App\Http\Middleware;

use App\Api\Models\AdminModel;
use App\Helper\DBRSAUtil;
use App\V3\V3_1\Models\SystemConfigModel;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class LoginLimit
{
    /**
     *
     * @param Request $request
     * @param Closure $next
     * AUTHOR  : Sun Wu
     * DateTime: 2022/2/24 11:24
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function handle(Request $request, Closure $next)
    {
        $token = $request->header('token');
        if(empty($token)){
            echo json_encode([
                'code' => 2,
                'msg' => 'token获取失败',
                'data' => '',
            ],JSON_UNESCAPED_UNICODE);die;
        }
        $array = explode(' ',$token);
        //私钥获取
        $private = SystemConfigModel::getConfigValue('private');
        $rsadata = DBRSAUtil::rsaDecrypt($array[1], $private);
        $rsadata = json_decode($rsadata,true);

        if(!empty(Redis::get('admin_array'))) {
            Redis::SETEX('admin_array', 86400*15, Redis::get('admin_array'));
            if(in_array($rsadata['userId'], json_decode(Redis::get('admin_array'), true))) {
                return response()->json([
                    'code' => 4,
                    'msg' => '权限信息变更，请重新登录后方可使用',
                    'data' => ''
                ]);
            }
        }

        $userInfo = AdminModel::where('id', $rsadata['userId'])->first();

        if($userInfo['delete_flag'] == 1) {
            return response()->json([
                'code' => 7,
                'msg' => '账号不存在或已被删除',
                'data' => ''
            ]);
        }

        if(!isset($rsadata['is_default_code'])) {
            return response()->json([
                'code' => 2,
                'msg' => 'token验证失败,请重新登录',
                'data' => ''
            ]);
        }

        if(!$rsadata['is_default_code']) {
            if(in_array($rsadata['type'], [1,2,4,5])) {
                if(Redis::GET($rsadata['userId'].'_app') != $array[1]) {
                    return response()->json([
                        'code' => 6,
                        'msg' => '您已在别处登陆，请重试',
                        'data' => ''
                    ]);
                }

                //重置redis有效期
                Redis::SETEX($rsadata['userId'].'_app', 86400*15, $array[1]);
            }
            else {
                if(Redis::GET($rsadata['userId'].'_pc') != $array[1]) {
                    return response()->json([
                        'code' => 6,
                        'msg' => '您已在别处登陆，请重试',
                        'data' => ''
                    ]);
                }

                //重置redis有效期
                Redis::SETEX($rsadata['userId'].'_pc', 86400*15, $array[1]);
            }
        }

        return $next($request);
    }
}
